package com.erpeng.demo.controller;

import com.erpeng.demo.vo.AppJclTxlVo;
import freemarker.core.ParseException;
import freemarker.template.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: controller
 * @Author erpeng
 * @create 2020-06-12
 * @Description:
 */

@RestController
@Slf4j
public class ExportController {
    @RequestMapping("/exportWord")
    public void exportWord(HttpServletRequest req, HttpServletResponse resp) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setDefaultEncoding("utf-8");
        /** 加载模板 **/
        // 这个方法在idea跑和打jar包部署都可以获取到模版
        configuration.setClassForTemplateLoading(this.getClass(), "/templates");
        //设置异常处理器 这样的话 即使没有属性也不会出错 如：${list.name}...不会报错
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        Template template = configuration.getTemplate("testXml.ftl");
        Map<String, Object> dataMap = new HashMap<>();
        /**1采集人员信息*/
        dataMap.put("cjrxm", "张三");
        dataMap.put("cjrdh", "13666666666");
        dataMap.put("cjrsfz", "421124199506062412");
        //造点测试数据 通讯表格的
        List<AppJclTxlVo> jclTxlVoList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            AppJclTxlVo appJclTxlVo = new AppJclTxlVo();
            appJclTxlVo.setXslx("受害人" + i);
            appJclTxlVo.setHmlx("手机号" + i);
            appJclTxlVo.setTxhm("1388888888" + i);
            appJclTxlVo.setTxlnc("小乖乖" + i);
            jclTxlVoList.add(appJclTxlVo);
        }
        /**通讯信息表格*/
        dataMap.put("jcTxl", jclTxlVoList);
        //造点测试数据 图片的
        List<String> sjbjtpImages = new ArrayList<>();
        sjbjtpImages.add(imageToBase64("D://test1.png"));
        sjbjtpImages.add(imageToBase64("D://test2.png"));
        sjbjtpImages.add(imageToBase64("D://test3.png"));
        dataMap.put("sjbjtpImages", sjbjtpImages);
        String fileName = "test.doc";
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            File wordFile = createDoc(dataMap, template);
            fin = new FileInputStream(wordFile);
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/msword");
            resp.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            out = resp.getOutputStream();
            byte[] buffer = new byte[1024];// 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (fin != null)
                fin.close();
            if (out != null)
                out.close();
        }
    }

    /**
     * 功能描述: 图片转base64
     *
     * @param: [path]
     * @return: java.lang.String
     * @Author: erpeng
     */
    public String imageToBase64(String path) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            log.error("加载图片未找到", e);
            e.printStackTrace();
        }
        try {
            data = new byte[in.available()];
            //注：FileInputStream.available()方法可以从输入流中阻断由下一个方法调用这个输入流中读取的剩余字节数
            in.read(data);
            in.close();
        } catch (IOException e) {
            log.error("IO操作图片错误", e);
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    @Autowired
    public static File createDoc(Map<?, ?> dataMap, Template template) {
        File f = new File("temp");
        try {
            //这个地方不能使用FileWriter因为需要指定编码类型否则生成的word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            template.process(dataMap, w);
            w.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return f;
    }
}

